#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
/*
 * gpiomon -r 0 24
 * */
#include "gpiod.h"
int gpio_read(int num, int offset)
{
  int old = 0, new = 0;
  struct gpiod_chip *chip = NULL;
  struct gpiod_line *line = NULL;
  chip = gpiod_chip_open_by_number(num);
  if (!chip) {
    printf("L%d", __LINE__);
    return 0;
  }
  line = gpiod_chip_get_line(chip, offset);
  if (!line) {
    fprintf(stderr, "L%d", __LINE__);
    return 0;
  }
  line = gpiod_chip_get_line(chip, offset);
  if (!line) {
    fprintf(stderr, "request output");
    return false;
  }
  gpiod_line_request_input(line, "example");
  new = gpiod_line_get_value(line);
  fprintf(stderr, "now:%d", new);
  while (1) {
    new = gpiod_line_get_value(line);
    if (new != old) {
      fprintf(stderr, "now:%d", new);
      old = new;
    }
    usleep(200000);
  }
}
int main (int argc, char **argv)
{
  int num = 0, offset = 13, ret;
  struct gpiod_chip *chip = NULL;
  struct gpiod_line *line = NULL;

  num = atoi(argv[2]);
  offset = atoi(argv[3]);
  if (!strcmp(argv[1], "read")) {
    gpio_read(num, offset);
  } else {
    fprintf(stderr, "invalid option");
    return 0;
  }
  chip = gpiod_chip_open_by_number(num);
  if (!chip) {
    fprintf(stderr, "L%d", __LINE__);
    return 0;
  }
  line = gpiod_chip_get_line(chip, offset);
  if (!line) {
    fprintf(stderr, "L%d", __LINE__);
    return 0;
  }
  ret = gpiod_line_request_output(line, "example",
      GPIOD_LINE_ACTIVE_STATE_LOW);
  ret = gpiod_line_set_value(line, 1);
  if (ret < 0) {
    fprintf(stderr, "L%d", __LINE__);
    gpiod_line_release(line);
    gpiod_chip_close(chip);
    return 0;
  }
  sleep(2);
  ret = gpiod_line_set_value(line, 0);
  if (ret < 0) {
    fprintf(stderr, "L%d", __LINE__);
    gpiod_line_release(line);
    gpiod_chip_close(chip);
    return 0;
  }
  sleep(1);
  gpiod_line_release(line);
  gpiod_chip_close(chip);

  return 0;
}

